package com.daftmaster.service.impl;

import com.daftmaster.entity.DeptEntity;
import com.daftmaster.mapper.DeptMapper;
import com.daftmaster.service.DeptService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Daft_V
 * @date 2022/3/24 10:18
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    DeptMapper deptMapper;

    @Override
    public Map<String, Object> queryDeptTree(int length, String dept_level) {
            Map<String, Object> map = new HashMap<>();
            List<DeptEntity> deptEntityListRoot;

            //判断是否为根节点
            if (length == 1) {
                deptEntityListRoot = deptMapper.queryDeptByLevelLength(length);
            } else {
                deptEntityListRoot = deptMapper.queryDeptByLevelLengthAndLevel(length, dept_level + ".%");
            }
            List<Map<String, Object>> deptList = new ArrayList<>();
            for (DeptEntity deptEntity : deptEntityListRoot
            ) {
                Map<String, Object> deptMap = new HashMap<>();
                deptMap.put("id", deptEntity.getId());
                deptMap.put("dept_name", deptEntity.getDept_name());
                deptMap.put("dept_level", deptEntity.getDept_level());

                //判断是否存在父id
                if(deptEntity.getParent_id()!=null){
                    deptMap.put("parent_id", deptEntity.getParent_id());
                }else{
                    deptMap.put("parent_id", "null");
                }
                List<Map<String, Object>> childList = new ArrayList<>();

                //递归调用
                Map<String, Object> deptChileMap = queryDeptTree(length + 2, deptEntity.getDept_level());
                if (deptChileMap != null && deptChileMap.toString().length() > 0) {
                    childList.add(deptChileMap);
                }
                deptMap.put("child", deptChileMap);
                deptList.add(deptMap);
            }
            map.put("data",deptList);
            return map;
    }
}
